# Based on the file created for Arch Linux by:
# Tobias Powalowski <tpowa@archlinux.org>
# Thomas Baechler <thomas@archlinux.org>
# Based on the file modified for Manjaro Linux by:
# Philip Müller <philm@manjaro.org>
# Guinux <guillaume@manjaro.org>
#
# originally from: https://github.com/manjaro/packages-core/blob/77c5092233f6fedf22a20fb4073d2ada68af4967/linux316/PKGBUILD
#
# "merged" with PKGBUILD from aur/linux-git which has:
# oldMaintainer: Boohbah <boohbah at gmail.com>
# Contributor: Tobias Powalowski <tpowa@archlinux.org>
# Contributor: Thomas Baechler <thomas@archlinux.org>

#
# modified for my own needs

#pkgbase="linux${_basever}" #linux317 or linux-git
pkgbase="linux-git"
#pkgname=('linux316' 'linux316-headers') #<- old and bad for fglrx!
#fixing install order so that compiling fglrx doesn't fail the first time!
pkgname=("${pkgbase}-headers" "$pkgbase" "${pkgbase}-docs")
_kernelname="${pkgbase#linux}" #-git
pkgver=4.8.rc8.r0.g08895a8
lfoldername="${pkgbase}"
pkgrel=1
arch=('x86_64')
#arch inside kernel folder (don't change!):
KARCH="x86"
url="https://www.kernel.org/"
license=('GPL2')
makedepends=('xmlto' 'docbook-xsl' 'kmod' 'inetutils' 'bc' 'git' 'pacman>4.1.2')
options=('!strip' 'ccache' '!distcc')
#so, distcc(and no ccache) works correctly when compiling this linuxgit (not so for firefox-hg though!)
#XXX: using ccache AND distcc will make every compilation on slave(s) fail! due to including some ccache path that exists only on master(in ~/.ccache/*)
#maybe search for this in man distcc: CCACHE_PREFIX="distcc"

manypatches=(
"1700_enable-thinkpad-micled.patch::http://sources.gentoo.org/cgi-bin/viewvc.cgi/linux-patches/genpatches-2.6/trunk/3.15/1700_enable-thinkpad-micled.patch"

acpi_no_spam_when_read_sensors.patch
dontdiff_update.patch
prevent_blackscreen_due_to_lacking_fbcon.patch
radeon_thermal.patch
1000_increase_scrollback_buffer_size_from_1024_to_4096_or_kernel_page_size.patch
1200_persistent_scrollback_buffer.patch
2000_bios_usb_legacy_Lenovo_Z575_avoid_CPU_Not_Responding.patch
2100_DIScrete_gfx_card_systemfreeze.patch
2200_fbcon_state_allocated_scrollbackbuffer.patch
#2300_DDEBUG_for_the_entire_acpi_folder.patch
2400_i8042_inside_virtualbox.patch
2500_lei8042.patch
2600_whichbug.patch
2700_isitnull.patch
2800_anotherNULLandpanic.patch
2900_prevent_dmesg_spam_from_preempt_notifier.patch
3100_kernel_undervolting.patch
3200_amd_errata_665.patch
3300_bug_119571.patch
#sync_cache_debug.patch
#dumpstack1.patch
#//XXX: temp commented out:
sync_cache_debug_and_disable_stopdisk.patch
#debug_deactivatesuper.patch #only needed when using the loaded .config which makes freeing pagecache pages take minutes

#showtrace_when_ohcifail.patch
#more_ohci_trace.patch
ohci_info.patch

rtc3.patch
rtc4.patch
rtc5.patch

#microcode_dontreboot.patch
)

presetfile="${pkgbase}.preset"
installfile="${pkgbase}.install"
vmlinuzfullpathfname="/boot/vmlinuz-${pkgbase}"
_initramfspartialpathfname="/boot/initramfs-${pkgbase}"
initramfsnormal="${_initramfspartialpathfname}.img"
initramfsfallback="${_initramfspartialpathfname}-fallback.img"

#TODO: use rsync to copy files into wherever, to avoid useless writes ie. in packages/  search for "install" in the current file

#avoid making compressed packages? aka faster
PKGEXT='.pkg.tar'
#or the default(from /etc/makepkg.conf), make compressed packages:
#PKGEXT='.pkg.tar.xz'

source=(
####"${lfoldername}::git+https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git#commit=694d0d0"
###"${lfoldername}::git+https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git#commit=86a1679"
"${lfoldername}::git+https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git"

"config.x86_64"
"${installfile}"

# standard config file for mkinitcpio ramdisk
"${presetfile}"

#'1700_enable-thinkpad-micled.patch::http://sources.gentoo.org/cgi-bin/viewvc.cgi/linux-patches/genpatches-2.6/trunk/3.15/1700_enable-thinkpad-micled.patch'

${manypatches[@]}
)
#run updpksums to automatically update these
#src: https://wiki.archlinux.org/index.php/makepkg#Generate_new_checksums
#problem is that it kill my spacing! those horizontal lines also
sha512sums=('SKIP'
            '422e9b21ca88ce1d24b0ee86873a296e38092d236e30afc7cf98678926761f624bc4111fbcacc8a608c735da31fd2cc86a6f42a71551eb8c8abc6f5b26f15833'
            '48a2d94108ec9dd0e8411330506d30d194f7e89c97e0f13537853359f0d16f2b8e32599008cba87b9e6522323ba952538286d6e4b85e0d222604d1f8ccdd0c45'
            '99dcd30805ddefe9fe6eba0316c29366442509f2727434e40a064eb7ec77bc211a7f75b356284fa2c358b09b13580fa073c493b629a2d92ebdf376d9894ec080'
            'bb62d66a95e2d27378433d0f9c2fc7943bbcd655a89952fc25ef28d5796b8d65ca6c9c48bc70d40d71daada20707b266f781f57ba71950009b32cb6d58e155d0'
            '37165798bf8cef81ddb8caa02c7775d28e8ae01c9c90720d1886061385f86663806b4f3ab61cf65187b1b0c5d2bfab20305455eec93c3eecb035d5aebf2a518c'
            '0cc382d790076c5c0abffd6e7643697f69bbf57f175eb2694f80dd800e1cb9eb03d086c46ba64025a8be1c4223caf7c1d6292ae856d21cd76975f2f47c62f722'
            '9a616b2763a24c05ed597812565218c6edd5111a99612ad5fa0f284eed4a5c476e0e0545ebbf4964c05a6c70c29a3d11b70ca00d34539b2e94b87fd0532135f9'
            'e77667ed4cf72cd155da524e2d04750fa2c3ffa2192cd0ddff4c1b89ccfccfaf1f11182837507069f66325b20be4bb5e5579235c78262cec3abd106b225f63b9'
            '38718c7ffddedcdedc52fa07eb5686e7d4841b4c6fed8cd18e899015b3bb672e5acd4aea4c20be88b8abce3cc2adb14c34f5374c99f6f7197178528e7af52e8c'
            '2a197b5b9c297e37cf631f9273dfbdd0e1b6e6d42517977246afabbb010d6c58b6a8705ecb09af47727121c166cab67e72212d24ddfe6333e5a983f28d0a5501'
            '1c7a7644497aa904f2ac22178ba5d2c8fd2024db887c33d5ddd87e3926a15063eae9ac9c22b68c76d3b1781a8f507f0d7f756528aae6799b3d210e26dddcea20'
            '62c76a86ca0a7b3a8345f21f1aec66281bc5a9a2a498ab5c19720c592b899e5dda23e9542147a2268e19a08c1132dd78208f83842d36a972f2ba39f1ab8ef48f'
            '6c7486ef1f705c578a207280aa38c3dcf2e4bfd3c0b48db07a9b0d0c0a6076788082184fdf4b465aaf3cb449c4197d2d5b22cddbf41be9ee16b1d3e339e15e68'
            '863c616dfc8648c6462a29c20a2006a0c69b37564b60d5db67c920dd45f00b02f1a767c534fefbb70cacd518ee5c76eb38acc09e02a201130363d250a47aae9f'
            '4fd9d73af452a3cd594fa37d77b8887c5c195e22db623d76334454c4b07569ab6b16454ff20c579f6fd8e83ae9bc7a6a3f78cbdab10267f7464bafa43367cb66'
            '8f69ffbac1116fa80d8eaac017452c4a4ef51a17d08a82cf1d5f8b1a640ca3c5cca205936814c9f09b7e2096b5feafbe689173bfca5772c87741fb3ec183b99b'
            'afc9b207b23ed989efd137294f0f6466e5dbfdac8e40c6c8b7a3db2d1e55b1ad11833f511e7d187a5b8db666cf4b555baf6fe735852243b5b6a64ec89fd7a4f6'
            'ea43190a8627a5de9d5836a36af538d8b4489e30731d090f4c6210279e4062e9ed9266b19d60fe5347d4d313a6ec7c41492e8b082c456f8dc14c00ef97bb5851'
            '2508151b88e8f07644de1252f8af31c7d8c41fb026c120ea6a6c2633c0b22c669c560b451f40ced84b9c88006e86b2ef3f3ee57bc9baeaea3688b9eb4273abd4'
            '772ee9031ea20b63ce2743afa960d2a15e3e844e0641a613545f436f9e41514638d5730417efb5552d03b98577220e0255508ca036f68abc6d41210491e4cf93'
            '8dd64be5273865e80748190df00b900747bea42853f80725f658e8d4ce85f92a9df88a8288689b8a35e7d71582dc45d8fec277edb561e1a6fe876b4ab526eade'
            'a5c3add10462141e8a3dd972f55fe5a41150eb413af2904d0a799a8a543c7db4b854a0a1576be30fe6dbeb5099190cdf88f4452755578061c542a20a231eb3ed'
            'efc3e2d82cac43dbe62697d3dca9a4172fd91a2b03e20d009b849f9fce3bde0ef06f24a268411fd29b6e84260b816c244840a10c320def71697ad2e6c859f0e5'
            '45495b6737703a01fb39dda7ae68686010ddff45309526d8eb55c11d4776a427cdfbf17ea5896d9b1a1f2a395082be20fe1095d5f90f46aedf4ef237f48b71e0'
            '7fbcd37e937264432e732ef0d32b70db2c910f1b8f9e507f6fce30fb4984cbd0fdb1960e3ff00ea6310b48ba96038e6e97c53bfbdceab66fb5ae9b4f05e7de94'
            '786b1d12c223c0e3e323ebffa4367ec27aa016aab6a7751f4059182573a89af22f6468e6335c1a59e163a9516b8ba492bd05762a716f28e563ce6347df753f9a'
            '883c280537d887ec91a2b8405b650f1109af28d54a9b8c128d2153a7577509a6feb13092658848e3a9eba6b8e180acfd65edc8018504a54b159869b4866c0b7f')

pkgver() {
  cd "${pkgbase}"
  git describe --long | sed -E 's/^v//;s/([^-]*-g)/r\1/;s/-/./g'
}


generic_patch() {
  # $1 which patch
  # $2- which params to the patch command
  local lepatch="$1"
  shift
  local params=("$@")
  msg2 "Applying patch: ${lepatch}"
  patch "${params[@]}" -i "${lepatch}"
}

apply_le_patch() {
  # $1 which patch
  # $2- which extra params to the patch command
  generic_patch "$@" -Np1
}

dryrun_patch() {
  # $1 which patch
  # $2- which extra params to the patch command
  apply_le_patch "$@" --dry-run >/dev/null 2>&1
}

onlyfilename() {
  [[ $# -eq 1 ]]
  echo -n "${1%%::*}"
}


prepare() {
  if [ "${CARCH}" != "x86_64" ]; then
    echo "unhandled case when not 64bit"
    exit 1
  fi

  dest1="${srcdir}/${lfoldername}"

#  if [ -d ${dest1} ]; then
    #backup previous existing one - this doesn't work for git because it's using the same folder: linux-git
#    mv -v ${dest1} $(mktemp -d --tmpdir="${srcdir}" linux-${pkgver}.previousXXXXXXXX )
#  fi

  #`pwd` is already ${srcdir} when prepare() is called
  cd ${dest1}

  #msg "restore my USB read speeds"
  #git revert -n 6a38fa0e3c94dfd1394a71a2d47c9c4d47367374

#  if diff -q "${srcdir}/config.x86_64" ".config"; then

#  fi

  #emacs: this cleans the folder of .config file ALSO!
#  time make mrproper

#patch if needed else ignore:

#done: find a way to ignore reversed patches but still err if some hunks fail
#done: even worse issue, some hunks are applied, so a patch is partially applied
#TODO: find a way to detect if the patch was fully applied - tough 'cause would have to parse each file mentioned within the patch and check if patching it failed and if so check if reversing the patch then applying it again yields the existing file - meh I don't wanna do it! too hacky!
  # add Gentoo patches
#  if ! dryrun_patch "${srcdir}/1700_enable-thinkpad-micled.patch"; then
#    error "patch cannot be (re)applied"
#    exit 3
#  else
#    if ! apply_le_patch "${srcdir}/1700_enable-thinkpad-micled.patch"; then
#      error "cannot apply patch - totally unexpected this here"
#      exit 103
#    fi
#  fi

  # add my patches
  # test if all patches can be applied!
  local _failpatch="n"
  for each in ${manypatches[@]}; do
    #    if ! patch --dry-run -Np1 -i "${srcdir}/${each}"; then
    local _fn1="$(onlyfilename "${srcdir}/${each}")"
    if ! dryrun_patch "${_fn1}"; then
      warning "cannot (re)apply patch: '${_fn1}'"
      _failpatch="y"
      break
    fi
  done
  # if all can be applied, then apply them
  if [ "$_failpatch" != "y" ]; then
    msg "Applying a bunch of patches"
    for each in ${manypatches[@]}; do
      local _fn2="$(onlyfilename "${srcdir}/${each}")"
      if ! apply_le_patch "${_fn2}"; then
        error "Unable to apply patch '${_fn2}'\nThis is not supposed to happen!"
        exit 104
      fi
    done
  else
    error "Cannot proceed towards applying all the patches!"
    exit 4
  fi


  #FIXME don't reboot on boot
#  git revert -n 88b2f634028f1f38dcc3d412e10ff1f224976daa

  #emacs
  #time make nconfig

  if [ ! -e ".config" ]; then
    cat "${srcdir}/config.x86_64" > ".config"
  fi


  # don't run depmod on 'make install'. We'll do this ourselves in packaging
  #TODO: find better way to prevent this from adding a line every time!
  local _sdm="scripts/depmod.sh"
  local _marker='(*HG*@EYHUDKPADasd42f'
  if ! grep -q -s "${_marker}" -- "${_sdm}" 2>/dev/null; then
    sed -i "2iexit 0\\n#$_marker" "${_sdm}"
  fi

  # normally not needed
  #make clean

  #msg "Just press F9 and save when asked!"
  #must happen before prepare OR else we get prompted for new options
  #make nconfig # new CLI menu for configuration

  # keep defaults for the NEWly added kernel options
  yes "" | make config >/dev/null

  # get kernel version FIXME: is this needed? or maybe only in build?
  make prepare

  # load configuration
  # Configure the kernel. Replace the line below with one of your choice.
  #make menuconfig # CLI menu for configuration

  #emacs, just save and exit to make sure any new additions get their defaults
  #this doesn't seem necessary anymore!!
  #make nconfig # new CLI menu for configuration

  #make xconfig # X-based configuration
  #make oldconfig # using old config from previous kernel version
  # ... or manually edit .config

  # rewrite configuration
  # yes "" | make config >/dev/null

  #emacs, when including some firmware(builtin) the folders must exist in kernel src tree under firmware, else errors of not found happen during build
  mkdir -p firmware/{amd-ucode,rtl_nic}

}

build() {
  cd "${srcdir}/${lfoldername}"

  #FIXME: apparently, if the pkgver just changed due to --incremental or new commits being pulled, then this pkgver value used here is the old one, and as an effect uname will show old pkgver and also cannot load the modules and no warnings/errors are shown, for example with ark3116 module - also because the modules in the old folder are removed when installing new pkgver version; XXX: apparently this only happened when running ./rePREPARE script, but not when ./2upd (only had to run it once and it worked: ark3116 is where it should be)
  # set localversion to git commit
  sed -i "s|CONFIG_LOCALVERSION=.*|CONFIG_LOCALVERSION=\"-${pkgver##*.}\"|g" ./.config
  sed -i "s|CONFIG_LOCALVERSION_AUTO=.*|CONFIG_LOCALVERSION_AUTO=n|" ./.config

  # set extraversion to release candidate version, or blank
  _rcver=${pkgver%.*.*}
  _rcver=${_rcver##*.}
  if [[ ${_rcver} == rc* ]]; then                                               
    sed -ri "s|^(EXTRAVERSION =).*|\1 -${_rcver}|" Makefile
  fi

  # build!
  #make ${MAKEFLAGS} LOCALVERSION= bzImage modules
  #

#  make ${MAKEFLAGS} EXTRA_CFLAGS="-Ofast -flto" LOCALVERSION= bzImage modules
#-flto causes a ton of these:
#  HOSTCC  scripts/mod/file2alias.o
#scripts/mod/file2alias.c: In function ‘do_usb_entry’:
#scripts/mod/file2alias.c:193:102: error: ‘OFF_usb_device_id_match_flags’ undeclared (first use in this function)
#  DEF_FIELD(symval, usb_device_id, match_flags);

  make ${MAKEFLAGS} EXTRA_CFLAGS="-pipe -Wno-trigraphs -fno-schedule-insns2 -fno-delete-null-pointer-checks -fomit-frame-pointer -Ofast" LOCALVERSION= bzImage modules
  #works!

  #make ${MAKEFLAGS} EXTRA_CFLAGS="-pipe -march=native -Wno-trigraphs -fno-delete-null-pointer-checks -mtune=native -fomit-frame-pointer -Ofast" LOCALVERSION= bzImage modules
  #-fno-schedule-insns2
  #/usr/bin/ld: Setup too big!
  #XXX it's because of one or both of: -march=native -mtune=native

  #make ${MAKEFLAGS} EXTRA_CFLAGS="-pipe -march=native -Wno-trigraphs -fno-schedule-insns2 -fno-delete-null-pointer-checks -mtune=native -fomit-frame-pointer -Ofast" LOCALVERSION= bzImage modules
  #  LD      arch/x86/boot/setup.elf
  #/usr/bin/ld: Setup too big!


  #make ${MAKEFLAGS} EXTRA_CFLAGS=-Os LOCALVERSION= bzImage modules
  #real 15m40.085s
  #user  35m37.491s
  #sys 3m51.649s
  #actually I C-c -ed it at some point because it seemed to be make -j1 but wasn't! was just using 1 core at some point, so total time is longer than seen above!


  #make ${MAKEFLAGS} EXTRA_CFLAGS=-W LOCALVERSION= bzImage modules
  # 22: Newly-added code has been compiled with `gcc -W' (use "make
  #  EXTRA_CFLAGS=-W").  This will generate lots of noise, but is good for
  #  finding bugs like "warning: comparison between signed and unsigned".
  # src: Documentation/SubmitChecklist
  #THAT SPAM IS TOO CRAZY!!!

}

package_linux-git() {

pkgdesc="The Linux kernel and modules (git version)"
#pkgdesc="The ${pkgbase/linux/Linux} kernel and modules"
depends=('coreutils' 'linux-firmware' 'kmod' 'mkinitcpio>=0.7' 'cpio')
#"${pkgbase}-headers")
optdepends=('crda: to set the correct wireless channels of your country')
#provides=("linux=${pkgver}")
provides=("linux${_kernelname}=${pkgver}" "linux=${pkgver}")
conflicts=("linux${_kernelname}")
replaces=("linux${_kernelname}")
backup=("etc/mkinitcpio.d/${presetfile}")
install=${installfile}

cd "${srcdir}/${lfoldername}"

# get kernel version
_kernver="$(make LOCALVERSION= kernelrelease)"
_basekernel=${_kernver%%-*}
_basekernel=${_basekernel%.*}   
fullkname="${_basekernel}${_kernelname:--MANJAROed}"

if [ -z "${KARCH}" ]; then
  echo "KARCH isn't set!"
  exit 1
fi

if [ -z "$_kernver" ]; then
  echo "_kernver isn't set!"
  exit 2
fi

mkdir -p "${pkgdir}"/{lib/modules,lib/firmware,boot}
make LOCALVERSION= INSTALL_MOD_PATH="${pkgdir}" modules_install
cp "arch/${KARCH}/boot/bzImage" "${pkgdir}/${vmlinuzfullpathfname}"

# add kernel version FIXME: why do we need this?
if [ "${CARCH}" = "x86_64" ]; then
  echo "${pkgver}-${pkgrel}-MANJARO x64" > "${pkgdir}/boot/${pkgbase}-${CARCH}.kver"
else
  echo "${pkgver}-${pkgrel}-MANJARO x32" > "${pkgdir}/boot/${pkgbase}-${CARCH}.kver"
fi

# set correct depmod command for install
echo "# Autogenerated from '${startdir}/${install}' on `date`" > "${startdir}/${install}.pkg"
cat -- "${startdir}/${install}" >> "${startdir}/${install}.pkg"
#cp -f "${startdir}/${install}" "${startdir}/${install}.pkg"
true && install=${install}.pkg
sed \
  -e  "s/KERNEL_NAME=.*/KERNEL_NAME=${_kernelname}/" \
  -e  "s/KERNEL_VERSION=.*/KERNEL_VERSION=${_kernver}/" \
  -i "${startdir}/${install}"

# install mkinitcpio preset file for kernel
install -D -m644 "${srcdir}/${presetfile}" "${pkgdir}/etc/mkinitcpio.d/${presetfile}"
sed \
  -e "1s|'linux.*'|'${pkgbase}'|" \
  -e "s|ALL_kver=.*|ALL_kver=\"${vmlinuzfullpathfname}\"|" \
  -e "s|default_image=.*|default_image=\"${initramfsnormal}\"|" \
  -e "s|fallback_image=.*|fallback_image=\"${initramfsfallback}\"|" \
  -i "${pkgdir}/etc/mkinitcpio.d/${presetfile}"

# remove build and source links
rm -f "${pkgdir}"/lib/modules/${_kernver}/{source,build}
# remove the firmware FIXME: don't we need this 'cause it's newer?
rm -rf "${pkgdir}/lib/firmware"
# gzip -9 all modules to save 100MB of space  #emacs: don't waste my time:
#find "${pkgdir}" -name '*.ko' -exec gzip -9 {} \;
# make room for external modules
ln -s "../extramodules-${fullkname}" "${pkgdir}/lib/modules/${_kernver}/extramodules"
# add real version for building modules and running depmod from post_install/upgrade
mkdir -p "${pkgdir}/lib/modules/extramodules-${fullkname}"
echo "${_kernver}" > "${pkgdir}/lib/modules/extramodules-${fullkname}/version"

# Now we call depmod...
#depmod --errsyms -b "${pkgdir}" -F System.map "${_kernver}"
depmod -b "${pkgdir}" -F System.map "${_kernver}"

# move module tree /lib -> /usr/lib
mkdir -p "${pkgdir}/usr"
mv "${pkgdir}/lib" "${pkgdir}/usr/"

# add vmlinux
install -D -m644 vmlinux "${pkgdir}/usr/lib/modules/${_kernver}/build/vmlinux" 
msg2 "removing msr module, moving to $USER ~/build/amdmsrtweaker-lnx/"
mv -- "${pkgdir}/usr/lib/modules/${_kernver}/kernel/arch/x86/kernel/msr.ko" ~/build/amdmsrtweaker-lnx/
#emacs:
# save .config so that *.install file knows if to prepend microcode before firmware (FIXME: checking not yet implemented)
cp "${srcdir}/${lfoldername}/.config" "${pkgdir}/kernel-${pkgver}.config"

#emacs:
#PLACEHOLDER_FOR_EARLY_LOAD_CPU_MICROCODE
#here we should edit *.install file (not *.install.pkg file) so that we place the call to prepend microcode to initramfs*.img file or not place it, depending on the early load config option being set in the .config
#FIXME: currently assuming we need to prepend the microcode all the time, which is done from the .install file (see that function with microcode in its name)

}

package_linux-git-headers() {
#pkgdesc="Header files and scripts for building modules for ${pkgbase/linux/Linux} kernel"
#provides=("linux-headers=$pkgver")
pkgdesc="Header files and scripts for building modules for Linux kernel (git version)"
provides=("linux${_kernelname}-headers=${pkgver}" "linux-headers=$pkgver")
conflicts=("linux${_kernelname}-headers")
replaces=("linux${_kernelname}-headers")




cd "${srcdir}/${lfoldername}"

# get kernel version
_kernver="$(make LOCALVERSION= kernelrelease)"

if [ -z "$KARCH" ]; then
  echo "KARCH isn't set!"
  exit 1
fi

if [ -z "$_kernver" ]; then
  echo "_kernver isn't set!"
  exit 2
fi
#pwd
#set -x
#env
#set
#exit 2
install -dm755 "${pkgdir}/usr/lib/modules/${_kernver}"

install -D -m644 Makefile \
  "${pkgdir}/usr/lib/modules/${_kernver}/build/Makefile"
install -D -m644 kernel/Makefile \
  "${pkgdir}/usr/lib/modules/${_kernver}/build/kernel/Makefile"
install -D -m644 .config \
  "${pkgdir}/usr/lib/modules/${_kernver}/build/.config"

mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/include"

for i in acpi asm-generic config crypto drm generated keys linux math-emu \
  media net pcmcia scsi sound trace uapi video xen; do
cp -a include/${i} "${pkgdir}/usr/lib/modules/${_kernver}/build/include/"
  done

  # copy arch includes for external modules
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/arch/${KARCH}"
  cp -a arch/${KARCH}/include "${pkgdir}/usr/lib/modules/${_kernver}/build/arch/${KARCH}/"

  # copy files necessary for later builds, like nvidia and vmware
  cp Module.symvers "${pkgdir}/usr/lib/modules/${_kernver}/build"
  cp -a scripts "${pkgdir}/usr/lib/modules/${_kernver}/build"

  # fix permissions on scripts dir
  chmod og-w -R "${pkgdir}/usr/lib/modules/${_kernver}/build/scripts"
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/.tmp_versions"

  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/arch/${KARCH}/kernel"

  cp "arch/${KARCH}/Makefile" "${pkgdir}/usr/lib/modules/${_kernver}/build/arch/${KARCH}/"

  if [ "${CARCH}" = "i686" ]; then
    cp "arch/${KARCH}/Makefile_32.cpu" "${pkgdir}/usr/lib/modules/${_kernver}/build/arch/${KARCH}/"
  fi

  cp "arch/${KARCH}/kernel/asm-offsets.s" "${pkgdir}/usr/lib/modules/${_kernver}/build/arch/${KARCH}/kernel/"

  # add docbook makefile
  install -D -m644 Documentation/DocBook/Makefile \
    "${pkgdir}/usr/lib/modules/${_kernver}/build/Documentation/DocBook/Makefile"

  # add dm headers
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/md"
  cp drivers/md/*.h "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/md"

  # add inotify.h
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/include/linux"
  cp include/linux/inotify.h "${pkgdir}/usr/lib/modules/${_kernver}/build/include/linux/"

  # add wireless headers
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/net/mac80211/"
  cp net/mac80211/*.h "${pkgdir}/usr/lib/modules/${_kernver}/build/net/mac80211/"

  # add dvb headers for external modules
  # in reference to:
  # http://bugs.archlinux.org/task/9912
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/dvb-core"
  cp drivers/media/dvb-core/*.h "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/dvb-core/"
  # and...
  # http://bugs.archlinux.org/task/11194

  #emacs: these cause errors because they weren't compiled in, so avoid:
  #  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/include/config/dvb/"
  #  cp include/config/dvb/*.h "${pkgdir}/usr/lib/modules/${_kernver}/build/include/config/dvb/"

  # add dvb headers for http://mcentral.de/hg/~mrec/em28xx-new
  # in reference to:
  # http://bugs.archlinux.org/task/13146
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/dvb-frontends/"
  cp drivers/media/dvb-frontends/lgdt330x.h "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/dvb-frontends/"
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/i2c/"
  cp drivers/media/i2c/msp3400-driver.h "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/i2c/"

  # add dvb headers
  # in reference to:
  # http://bugs.archlinux.org/task/20402
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/usb/dvb-usb"
  cp drivers/media/usb/dvb-usb/*.h "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/usb/dvb-usb/"
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/dvb-frontends"
  cp drivers/media/dvb-frontends/*.h "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/dvb-frontends/"
  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/tuners"
  cp drivers/media/tuners/*.h "${pkgdir}/usr/lib/modules/${_kernver}/build/drivers/media/tuners/"

  # add xfs and shmem for aufs building
  #emacs: commented due to file not found (not compiled)
#  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/fs/xfs"
#  mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build/mm"
#  cp fs/xfs/xfs_sb.h "${pkgdir}/usr/lib/modules/${_kernver}/build/fs/xfs/xfs_sb.h"

  # copy in Kconfig files
  for i in $(find . -name "Kconfig*"); do
    mkdir -p "${pkgdir}"/usr/lib/modules/${_kernver}/build/`echo ${i} | sed 's|/Kconfig.*||'`
    cp ${i} "${pkgdir}/usr/lib/modules/${_kernver}/build/${i}"
  done

  chown -R root.root "${pkgdir}/usr/lib/modules/${_kernver}/build"
  find "${pkgdir}/usr/lib/modules/${_kernver}/build" -type d -exec chmod 755 {} \;

  # strip scripts directory
  find "${pkgdir}/usr/lib/modules/${_kernver}/build/scripts" -type f -perm -u+w 2>/dev/null | while read binary ; do
  case "$(file -bi "${binary}")" in
    *application/x-sharedlib*) # Libraries (.so)
      /usr/bin/strip ${STRIP_SHARED} "${binary}";;
    *application/x-archive*) # Libraries (.a)
      /usr/bin/strip ${STRIP_STATIC} "${binary}";;
    *application/x-executable*) # Binaries
      /usr/bin/strip ${STRIP_BINARIES} "${binary}";;
  esac
done

# remove unneeded architectures
rm -rf "${pkgdir}"/usr/lib/modules/${_kernver}/build/arch/{alpha,arc,arm,arm26,arm64,avr32,blackfin,c6x,cris,frv,h8300,hexagon,ia64,m32r,m68k,m68knommu,metag,mips,microblaze,mn10300,openrisc,parisc,powerpc,ppc,s390,score,sh,sh64,sparc,sparc64,tile,unicore32,um,v850,xtensa}

#conflict because Kconfig.* (3 files) exist already in the docs package!
rm -rf "${pkgdir}/usr/lib/modules/${_kernver}/build/Documentation/kbuild"
}

package_linux-git-docs() {
pkgdesc="Kernel hackers manual - HTML documentation that comes with the Linux kernel (git version)"
provides=("kernel${_kernelname}-docs=${pkgver}" "kernel-docs=$pkgver")
conflicts=("kernel${_kernelname}-docs")
replaces=("kernel${_kernelname}-docs")

cd "${srcdir}/${lfoldername}"

mkdir -p "${pkgdir}/usr/lib/modules/${_kernver}/build"
cp -al Documentation "${pkgdir}/usr/lib/modules/${_kernver}/build"
find "${pkgdir}" -type f -exec chmod 444 {} \;
find "${pkgdir}" -type d -exec chmod 755 {} \;

# remove a file already in linux package
rm -f "${pkgdir}/usr/lib/modules/${_kernver}/build/Documentation/DocBook/Makefile"
}

# vim:set ts=8 sts=2 sw=2 et:
